from flask import Blueprint, request
from models import db, User, Token
#from werkzeug.security import generate_password_hash, check_password_hash
import jwt

from datetime import datetime, timedelta
from functools import wraps
from utils.res import api_response
#from utils.scrypt import generate_pwd_hash,check_pwd_hash
import os

user_bp = Blueprint('user', __name__)

# 从配置文件中获取 JWT 密钥
from instance.config import Config
jwt_secret_key = Config.JWT_SECRET_KEY

# JWT 验证装饰器
def token_required(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        token = request.headers.get('Authorization')
        if not token:
            return api_response(401, "令牌丢失", None)
        try:
            token = token.split(" ")[1]  # 去掉 "Bearer " 前缀
            data = jwt.decode(token, jwt_secret_key, algorithms=["HS256"])
            user_id = data['user_id']
            user = User.query.get(user_id)
            if not user:
                return api_response(401, "令牌无效", None)
        except jwt.ExpiredSignatureError:
            return api_response(401, "令牌失效", None)
        except jwt.InvalidTokenError:
            return api_response(401, "令牌无效", None)
        
        return f(*args, **kwargs)
    return decorated


# 新增用户(仅限登录用户)
@user_bp.route('/users', methods=['POST'])
@token_required
def add_user():
    data = request.get_json()
    res = None
    if not data or 'name' not in data:
        return api_response(400, "请求新增的用户信息丢失",  res )
    
    name=data.get('name')
    if User.query.filter_by(name=name).first():
         return api_response(400, "用户名已存在",  res )
  
    new_user = User(
        name=data.get('name'),
        gender=data.get('gender','男'),
        age=data.get('age',18),
        bio=data.get('bio', '')
    )
    password = data.get('password','123456')
    new_user.set_password(password)
    
    db.session.add(new_user)
    db.session.commit()
    res= {'id': new_user.id}
    return api_response(200, "用户注册成功",  res )
   

# 用户登录
@user_bp.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    res = None
    if not data or 'name' not in data or 'password' not in data:
        return api_response(400, "请求注册的用户信息丢失",  res )
    
    name = data['name']
    password = data['password']
    
    user = User.query.filter_by(name=name).first()
    
    # 验证用户
    if not user or not user.check_password(password):
        return api_response(401, "用户信息有误", res)
    token = jwt.encode({'user_id': user.id, 'exp': datetime.now() + timedelta(hours=1)}, jwt_secret_key, algorithm="HS256")
    new_token = Token(token=token, user_id=user.id)
    db.session.add(new_token)
    db.session.commit()
    res = {"user": user.to_bio_dict(),"token":token}
    return api_response(200, "登录成功", res)

# 获取所有用户（仅限已登录用户）
@user_bp.route('/users', methods=['GET'])
@token_required
def get_users():
    users = User.query.all()
    res=[user.to_dict() for user in users]
    return api_response(200, "获取成功", res)
   
# 获取单个用户（仅限已登录用户）
@user_bp.route('/users/<int:user_id>', methods=['GET'])
@token_required
def get_user(user_id):
    user = User.query.get(user_id)
    if not user:
        return api_response(404, "用户不存在")

    res=user.to_bio_dict()
    return api_response(200, "用户信息获取成功", res)

# 更新用户信息（仅限已登录用户）
@user_bp.route('/users/<int:user_id>', methods=['PUT'])
@token_required
def update_user(user_id):
    user = User.query.get(user_id)
    if not user:
        return api_response(404, "用户不存在")
    
    data = request.get_json()
    if 'name' in data:
        user.name = data['name']
    if 'age' in data:
        user.age = data['age']
    if data.get('password'):
        user.set_password(data['password'])
    if 'gender' in data:
        user.gender =data['gender']
    if 'bio' in data:
        user.bio =data['bio']
    
    db.session.commit()
    res=user.to_dict()
    return api_response(200, "用户信息更新成功", res)
    

# 删除用户（仅限已登录用户）
@user_bp.route('/users/<int:user_id>', methods=['DELETE'])
@token_required
def delete_user(user_id):
    user = User.query.get(user_id)
    if not user:
        return api_response(404, "用户不存在")
       
    db.session.delete(user)
    db.session.commit()

    return api_response(200, "用户删除成功")

